package com.yisu.expressway.onedollar.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.pingplusplus.android.Pingpp;
import com.yisu.expressway.R;
import com.yisu.expressway.onedollar.model.OrderObj;
import com.yisu.expressway.onedollar.presenter.IPayPresenter;
import com.yisu.expressway.onedollar.presenter.impl.PayPresenterImpl;
import com.yisu.expressway.onedollar.utils.DateUtil;
import com.yisu.expressway.onedollar.view.IPayView;
import com.yisu.expressway.onedollar.widget.CountdownView;
import com.yisu.expressway.onedollar.widget.TitleView;
import com.yisu.expressway.ui.MultiButtonDialog;
import com.yisu.expressway.ui.SingleButtonAlertDialog;
import com.yisu.expressway.utils.SpannableUtil;
import com.yisu.expressway.utils.ToastUtil;

import java.text.ParseException;
import java.util.Date;

import butterknife.Bind;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

/**
 * Created by Kaven on 2016/12/19.
 */

public class PayActivity extends BasicActivity
        implements IPayView, CountdownView.OnCountdownEndListener,
        CountdownView.OnCountdownIntervalListener, RadioGroup.OnCheckedChangeListener {
    private static final String EXTRA_KEY_GOODS_NO = "extra_key_goods_no";
    private static final String EXTRA_KEY_GOODS_NAME = "extra_key_goods_name";
    private static final String EXTRA_KEY_GOODS_COST = "extra_key_goods_cost";
    private static final String EXTRA_KEY_ORDER_INFO = "extra_key_order_info";
    private static final String EXTRA_KEY_PERIODS_NUM = "extra_key_periods_num";
    private static final String EXTRA_KEY_JOIN_NUM = "extra_key_join_num";
    @Bind(R.id.title_bar)
    protected TitleView mTitleView;
    @Bind(R.id.cv_countdown)
    protected CountdownView mRemainCv;
    @Bind(R.id.tv_goods_name)
    protected TextView mGoodsNameTv;
    @Bind(R.id.tv_goods_cost)
    protected TextView mGoodsCostTv;
    @Bind(R.id.tv_amount)
    protected TextView mAmountTv;
    @Bind(R.id.tv_terms)
    protected TextView mTermsTv;
    @Bind(R.id.rg_pay)
    protected RadioGroup mPayRg;
    @Bind(R.id.rb_alipay)
    protected RadioButton mAlipayRb;
    @Bind(R.id.rb_weixin)
    protected RadioButton mWeixinRb;
	@Bind(R.id.tv_pay_now)
	protected TextView mPayNowTv;
    @Bind(R.id.cb_terms)
    protected CheckBox mTermsCb;
    private IPayPresenter mPresenter;
    private String mGoodsName;
    private double mGoodsCost;
    private OrderObj mOrder;
    private long mPeriodsNum;
    private long mJoinNum;
    private long mGoodsNo;
    private boolean bTermsReaded;

    public static void launch(Context context, String goodsName, double cost, OrderObj orderObj, long periodsNum,long joinNum,long goodsNo) {
        Intent intent = new Intent(context, PayActivity.class);
        intent.putExtra(EXTRA_KEY_GOODS_NAME, goodsName);
        intent.putExtra(EXTRA_KEY_GOODS_COST, cost);
        intent.putExtra(EXTRA_KEY_ORDER_INFO, orderObj);
        intent.putExtra(EXTRA_KEY_PERIODS_NUM, periodsNum);
        intent.putExtra(EXTRA_KEY_JOIN_NUM, joinNum);
        intent.putExtra(EXTRA_KEY_GOODS_NO, goodsNo);
        context.startActivity(intent);
    }

    @OnClick({ R.id.tv_pay_now, R.id.tv_terms })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_pay_now:
                if (mWeixinRb.isChecked()){
                    showToast("敬请期待");
                    return;
                }

                if (!bTermsReaded) {
                    showToast("请勾选服务协议");
	                return;
                }
                mPresenter.getPaymentData(mOrder.orderId, mPresenter.getPayChannel());
                break;
            case R.id.tv_terms:
                jump2TermsPage();
                break;
            default:
                break;
        }
    }

    @OnCheckedChanged({ R.id.cb_terms })
    protected void onCheckChanged(CompoundButton buttonView, boolean check) {
        switch (buttonView.getId()) {
            case R.id.cb_terms:
                bTermsReaded = check;
                break;
            default:
                break;
        }
    }

    @Override
    protected int getThemeId() {
        return R.style.OneDollarTheme;
    }

    @Override
    protected int getInflateLayoutId() {
        return R.layout.activity_pay;
    }

    @Override
    protected void initPresenter() {
        mPresenter = new PayPresenterImpl(this, this);
        mPresenter.init();
    }

    @Override
    protected void releasePresenter() {
        if (mPresenter != null) {
            mPresenter = null;
        }
    }

    @Override
    protected void getIntentData(Intent intent) {
        String goodsName = intent.getStringExtra(EXTRA_KEY_GOODS_NAME);
        double goodsCost = intent.getDoubleExtra(EXTRA_KEY_GOODS_COST, -1);
        OrderObj orderObj = (OrderObj) intent.getSerializableExtra(EXTRA_KEY_ORDER_INFO);
        if (goodsCost < 0 || orderObj == null) {
            finish();
            return;
        }
        mGoodsName = goodsName;
        mGoodsCost = goodsCost;
        mOrder = orderObj;
        mPeriodsNum =  intent.getLongExtra(EXTRA_KEY_PERIODS_NUM, -1);
        mJoinNum =  intent.getLongExtra(EXTRA_KEY_JOIN_NUM, -1);
        mGoodsNo =  intent.getLongExtra(EXTRA_KEY_GOODS_NO, -1);
    }

    @Override
    protected void getSavedBundleData(Bundle bundle) {

    }

    @Override
    protected void initViews() {
        setCountDownView();
        mTermsTv.setText(
                SpannableUtil.setHighLight(this, getString(R.string.one_dollar_terms_remind),
                        getString(R.string.one_dollar_terms_prefix), R.color.oneDollarTextGrey));
        mGoodsNameTv.setText(mGoodsName);
        String format = String.format(getString(R.string.one_dollar_pay_fade_cost), mJoinNum);
        mGoodsCostTv.setText(format);
        format = String.format(getString(R.string.one_dollar_pay_real_cost), mGoodsCost);
        mAmountTv.setText(format);
        bTermsReaded= mTermsCb.isChecked();
	    mPresenter.changeOrderPaymentChannel(mOrder.orderId,mPresenter.getPayChannel());
    }

    private void setCountDownView() {
        if (mOrder == null) {
            return;
        }

        try {
            Date dateNow = DateUtil.stringToDate(mOrder.currentSystemTime,
                    DateUtil.PATTERN_DATE_TIME);

            Date deadLine = DateUtil.stringToDate(mOrder.paymentDeadlineTime,
                    DateUtil.PATTERN_DATE_TIME);
            if (dateNow != null && deadLine != null && dateNow.before(deadLine)) {
                mRemainCv.setVisibility(View.VISIBLE);
                mRemainCv.start(deadLine.getTime() - dateNow.getTime());
                mRemainCv.setOnCountdownEndListener(this);
                mRemainCv.setOnCountdownIntervalListener(1000, this);
            } else {
                mRemainCv.setVisibility(View.GONE);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showCancelConfirmDlg();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
    protected void bindEvents() {
        mTitleView.setOnTitleBarClickEvent(new TitleView.OnTitleBarClickEvent() {
            @Override
            public void onLeftClick(View view) {
                showCancelConfirmDlg();
            }

            @Override
            public void onTitleClick(View view) {

            }

            @Override
            public void onRightClick(View view) {

            }
        });
        mPayRg.setOnCheckedChangeListener(this);
    }

    @Override
    protected boolean isNeedLogin() {
        return false;
    }

    @Override
    protected void onLoginStateChange(boolean login) {

    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void jump2TermsPage() {
        startTargetActivity(OneDollarTermsActivity.class);
    }

    @Override
    public void jump2SuccessPage() {
        PaySuccessActivity.launch(this,mOrder.orderId, mGoodsName,mPeriodsNum,mJoinNum,mGoodsNo);
	    finish();
    }

    @Override
    public void showToast(String toastMsg) {
        if (TextUtils.isEmpty(toastMsg)) {
            return;
        }
        ToastUtil.showMessage(this, toastMsg);
    }

    @Override
    public void showLoadingDlg() {
        showLoading();
    }

    @Override
    public void dismissLoadingDlg() {
        dismissLoading();
    }

    @Override
    public void showCancelConfirmDlg() {
        final MultiButtonDialog multiButtonDialog = new MultiButtonDialog(this);
        multiButtonDialog.show();
        multiButtonDialog.setDialogTitle(R.string.one_dollar_payment_confirm);
        multiButtonDialog.setButtonColor(R.color.oneDollarCommon);
        multiButtonDialog.setContentText(R.string.one_dollar_payment_cancel_warnning);
        multiButtonDialog.setPositiveClickListener(new MultiButtonDialog.PositiveClickListener() {
            @Override
            public void onPositiveClick(String inputContent) {

                multiButtonDialog.dismiss();
                mPresenter.cancelOrder(mOrder.orderId);
                finish();
            }
        });
        multiButtonDialog.setNegativeClickListener(new MultiButtonDialog.NegativeClickListener() {
            @Override
            public void onNegativeClick(String inputContent) {
                multiButtonDialog.dismiss();
            }
        });
    }

    @Override
    public void onEnd(CountdownView cv) {
        showToast("支付有效时间已超时，该订单自动取消");
        mPresenter.cancelOrder(mOrder.orderId);
        finish();
    }

    @Override
    public void onInterval(CountdownView cv, long remainTime) {

    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_alipay:
                mAlipayRb.setChecked(true);
                mPresenter.changeOrderPaymentChannel(mOrder.orderId, PayPresenterImpl.CHANNEL_APLIPAY);
                break;
            case R.id.rb_weixin:
//                mWeixinRb.setChecked(true);
//                showToast("敬请期待");
//                mPresenter.changeOrderPaymentChannel(mOrder.orderId, PayPresenterImpl.CHANNEL_WEIXIN);
                break;
            default:
                break;
        }
    }
    private final String RESULT_SUCCESS = "success";
    private final String RESULT_FAIL = "fail";
    private final String RESULT_CANCEL = "cancel";
    private final String RESULT_INVALID = "invalid";
	/**
	 * onActivityResult 获得支付结果，如果支付成功，服务器会收到ping++ 服务器发送的异步通知。
	 * 最终支付成功根据异步通知为准
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		//支付页面返回处理
		if (requestCode == Pingpp.REQUEST_CODE_PAYMENT) {
			if (resultCode == Activity.RESULT_OK) {
				String result = data.getExtras().getString("pay_result");
                /* 处理返回值
                 * "success" - payment succeed
                 * "fail"    - payment failed
                 * "cancel"  - user canceld
                 * "invalid" - payment plugin not installed
                 */
				String errorMsg = data.getExtras().getString("error_msg"); // 错误信息
				String extraMsg = data.getExtras().getString("extra_msg"); // 错误信息

                switch (result){
                    case RESULT_SUCCESS:
                        jump2SuccessPage();
                        break;
                    case RESULT_FAIL :
                    case RESULT_INVALID:
                        showToast(result);
                        break;
                    case RESULT_CANCEL:
                        showCanceledByUserDlg();
                        break;
                }
			}
		}
	}

    private void showCanceledByUserDlg() {
        final SingleButtonAlertDialog dlg = new SingleButtonAlertDialog(this);
        dlg.show();
        dlg.setTitle(R.string.one_dollar_payment_failed);
        dlg.setButtonBgColor(R.color.oneDollarCommon);
        dlg.setContentText(R.string.one_dollar_payment_cancel_by_user_warnning);
        dlg.setPositiveClickListener(new SingleButtonAlertDialog.PositiveClickListener() {
            @Override
            public void onPositiveClick() {
                dlg.dismiss();
            }
        });
    }
}
